import {
    ScreenSpaceEventHandler,
    Event,
    Cartesian3,
    CallbackProperty,
    Color,
    DistanceDisplayCondition,
    NearFarScalar,
    VerticalOrigin,
    LabelStyle,
    ScreenSpaceEventType,
    Cartesian2,
    Math as CesiumMath,
    HorizontalOrigin
} from 'cesium';
import pointImage from '@/assets/images/point.png';
import deleteImage from '@/assets/images/delete.png';
class CesiumMeasureDistance {
    constructor(viewer) {
        this.viewer = viewer;
        this.initEvents();
        this.positions = []; // 已确定的坐标点
        this.tempPositions = []; // 临时坐标点（鼠标移动时的动态点）
        this.vertexEntities = []; // 所有顶点实体（起点、中间点、终点）
        this.moveVertexEntity = null; // 移动中的临时顶点（鼠标移动时的动态点）
        this.measureDistance = 0; // 测量结果
        this.isMeasure = false;
        this.lineEntity = null; // 线段实体
        this.allLineEntities = []; // 存储所有线段实体
        this.deleteButtonEntities = []; // 添加删除按钮实体数组
        this.currentMeasureGroupId = null; // 修改：初始化时不生成ID

        // 添加删除按钮的点击事件处理器
        this.clickHandler = new ScreenSpaceEventHandler(this.viewer.scene.canvas);
        this.clickHandler.setInputAction(this.handleEntityClick.bind(this), ScreenSpaceEventType.LEFT_CLICK);
    }

    // 初始化事件
    initEvents() {
        this.handler = new ScreenSpaceEventHandler(this.viewer.scene.canvas);
        this.MeasureStartEvent = new Event(); // 开始事件
        this.MeasureEndEvent = new Event(); // 结束事件
    }

    // 激活测量
    activate() {
        // 仅重置当前测量的临时数据，不清除之前的线路
        this.resetTempData();
        this.registerEvents();
        this.viewer.enableCursorStyle = false;
        this.viewer.scene.canvas.style.cursor = 'default';
        this.isMeasure = true;
        this.currentMeasureGroupId = Date.now().toString(); // 每次激活时生成新的ID
        this.MeasureStartEvent.raiseEvent();
    }

    // 禁用测量（仅移除事件，不清空图形，如需清空请调用clear()）
    deactivate() {
        if (!this.isMeasure) return;
        this.unRegisterEvents();
        this.viewer.scene.canvas.style.cursor = 'pointer';
        this.viewer.enableCursorStyle = true;
        this.isMeasure = false;
    }

    // 清空所有测量图形
    clear() {
        if (this.lineEntity) this.viewer.entities.remove(this.lineEntity);
        this.allLineEntities.forEach(entity => this.viewer.entities.remove(entity));
        this.allLineEntities = [];
        this.vertexEntities.forEach(entity => this.viewer.entities.remove(entity));
        this.vertexEntities = [];
        this.moveVertexEntity = null;
        this.positions = [];
        this.tempPositions = [];
        this.measureDistance = 0;
        this.deleteButtonEntities.forEach(entity => this.viewer.entities.remove(entity));
        this.deleteButtonEntities = [];
    }

    // 重置当前测量的临时数据
    resetTempData() {
        this.positions = [];
        this.tempPositions = [];
        if (this.moveVertexEntity) {
            this.viewer.entities.remove(this.moveVertexEntity);
            this.moveVertexEntity = null;
        }
        this.measureDistance = 0;
        if (this.lineEntity) {
            this.lineEntity.measureGroupId = this.currentMeasureGroupId;
            this.allLineEntities.push(this.lineEntity);
            this.lineEntity = null;
        }
    }


    // 创建线对象（临时预览）
    createLineEntity() {
        this.lineEntity = this.viewer.entities.add({
            polyline: {
                positions: new CallbackProperty(e => this.tempPositions, false),
                width: 2,
                material: Color.YELLOW,
                depthFailMaterial: Color.YELLOW,
                clampToGround: true // 线段贴地
            }
        });
    }

    // 创建顶点实体（通用方法，支持起点/中间点/终点）
    createVertexEntity(position, isStart = false, isEnd = false, measureGroupId) {
        const entityOptions = {
            position,
            point: {
                color: Color.FUCHSIA,
                pixelSize: 6,
                disableDepthTestDistance: 500
            },
            isMeasureVertex: true,
            measureGroupId: measureGroupId // 添加测量组ID
        };

        if (isStart || isEnd) {
            entityOptions.billboard = {
                image: pointImage,
                scaleByDistance: new NearFarScalar(300, 1, 1200, 0.4),
                distanceDisplayCondition: new DistanceDisplayCondition(0, 10000),
                verticalOrigin: VerticalOrigin.BOTTOM // 图标底部对齐坐标点
            };
        }

        const entity = this.viewer.entities.add(entityOptions);

        // 添加终点总距离标签（仅终点显示）
        if (isEnd && this.positions.length > 1) {
            entity.label = {
                text: `总距离：${this.calculateDistance(this.positions)}米`,
                scale: 0.5,
                font: 'normal 26px MicroSoft YaHei',
                distanceDisplayCondition: new DistanceDisplayCondition(0, 5000),
                scaleByDistance: new NearFarScalar(1000, 1, 3000, 0.4),
                verticalOrigin: VerticalOrigin.TOP, // 标签显示在图标上方
                style: LabelStyle.FILL_AND_OUTLINE,
                pixelOffset: new Cartesian2(0, 20), // 向上偏移20像素
                outlineWidth: 2,
                outlineColor: Color.WHITE
            };
        }


        return entity;
    }

    // 左键点击：添加固定点
    // 修改 leftClickHandler 方法，确保所有实体都关联到当前测量组
leftClickHandler(e) {
    const position = this.getValidPosition(e.position);
    if (!position) return;

    if (this.positions.length === 0) {
        // 第一个点：创建起点
        const startEntity = this.createVertexEntity(position, true, false, this.currentMeasureGroupId);
        startEntity.measureGroupId = this.currentMeasureGroupId; // 确保设置ID
        this.positions.push(position);
        this.vertexEntities.push(startEntity);

        // 创建临时线段
        this.createLineEntity();
        if (this.lineEntity) {
            this.lineEntity.measureGroupId = this.currentMeasureGroupId; // 为线段设置ID
        }

        // 创建临时移动顶点
        this.moveVertexEntity = this.viewer.entities.add({
            position,
            point: {
                color: Color.FUCHSIA.withAlpha(0.7),
                pixelSize: 8,
                disableDepthTestDistance: 500
            },
            measureGroupId: this.currentMeasureGroupId // 为移动点设置ID
        });
    } else {
        // 后续点：创建中间点
        const middleEntity = this.createVertexEntity(position, false, false, this.currentMeasureGroupId);
        middleEntity.measureGroupId = this.currentMeasureGroupId; // 确保设置ID

        // 添加中间距离标签
        middleEntity.label = {
            text: `${this.calculateDistance([this.positions[this.positions.length - 1], position])}米`,
            scale: 0.5,
            font: 'normal 24px MicroSoft YaHei',
            distanceDisplayCondition: new DistanceDisplayCondition(0, 5000),
            scaleByDistance: new NearFarScalar(1000, 1, 3000, 0.4),
            verticalOrigin: VerticalOrigin.BOTTOM,
            style: LabelStyle.FILL_AND_OUTLINE,
            pixelOffset: new Cartesian2(0, -30),
            outlineWidth: 2,
            outlineColor: Color.WHITE
        };
        this.positions.push(position);
        this.vertexEntities.push(middleEntity);
    }
    this.tempPositions = [...this.positions, position];
}

    // 鼠标移动：实时预览
    mouseMoveHandler(e) {
        if (!this.isMeasure || this.positions.length < 1) return;
        const position = this.getValidPosition(e.endPosition);
        if (!position) return;
        // 更新临时线段和移动顶点位置
        this.tempPositions = [...this.positions, position];
        if (this.moveVertexEntity) {
            this.moveVertexEntity.position = position;
        }
    }

    // 处理实体点击事件
handleEntityClick(click) {
    if (this.isMeasure) return; // 如果正在测量，不处理删除点击

    const pickedObject = this.viewer.scene.pick(click.position);
    if (pickedObject && pickedObject.id && pickedObject.id.isDeleteButton) {
        const measureGroupId = pickedObject.id.measureGroupId;
        this.deleteMeasureGroup(measureGroupId);
    }
}

// 删除指定ID的测量组
deleteMeasureGroup(measureGroupId) {
    // 删除线实体
    const lineToRemove = this.allLineEntities.find(entity => entity.measureGroupId === measureGroupId);
    if (lineToRemove) {
        this.viewer.entities.remove(lineToRemove);
        this.allLineEntities = this.allLineEntities.filter(entity => entity.measureGroupId !== measureGroupId);
    }

    // 删除顶点实体
    const verticesToRemove = this.vertexEntities.filter(entity => entity.measureGroupId === measureGroupId);
    verticesToRemove.forEach(entity => {
        this.viewer.entities.remove(entity);
    });
    this.vertexEntities = this.vertexEntities.filter(entity => entity.measureGroupId !== measureGroupId);

    // 删除删除按钮实体
    const buttonToRemove = this.deleteButtonEntities.find(entity => entity.measureGroupId === measureGroupId);
    if (buttonToRemove) {
        this.viewer.entities.remove(buttonToRemove);
        this.deleteButtonEntities = this.deleteButtonEntities.filter(entity => entity.measureGroupId !== measureGroupId);
    }
}

    // 创建删除按钮实体
createDeleteButton(position, measureGroupId) {
    const deleteButton = this.viewer.entities.add({
        position: position,
        billboard: {
            image: deleteImage,
            scale: 0.05,
            horizontalOrigin: HorizontalOrigin.CENTER,
            verticalOrigin: VerticalOrigin.CENTER,
            scaleByDistance: new NearFarScalar(300, 1, 1200, 0.4),
            distanceDisplayCondition: new DistanceDisplayCondition(0, 10000),
            pixelOffset: new Cartesian2(0, 30) // 向下偏移30像素
        },
        isDeleteButton: true,
        measureGroupId: measureGroupId
    });

    this.deleteButtonEntities.push(deleteButton);
    return deleteButton;
}

    // 右键点击：结束测量
rightClickHandler(e) {
    if (!this.isMeasure || this.positions.length < 1) {
        this.deactivate();
        return;
    }



    // 添加最后一个临时点为正式点（如果存在）
    if (this.tempPositions.length > this.positions.length) {
        const finalPosition = this.tempPositions[this.tempPositions.length - 1];
        this.positions.push(finalPosition);
    }

    // 只有当有至少两个点时才创建终点和线段
    if (this.positions.length >= 2) {
        // 创建终点实体（带总距离标签）
        const endEntity = this.createVertexEntity(this.positions[this.positions.length - 1], false, true, this.currentMeasureGroupId);
        this.vertexEntities.push(endEntity);

        // 固定线段为正式坐标（移除临时回调，使用固定坐标）
        if (this.lineEntity) {
            this.lineEntity.polyline.positions = this.positions;
            this.lineEntity.polyline.clampToGround = true;
            this.lineEntity.measureGroupId = this.currentMeasureGroupId;

            // 计算线段中点位置用于放置删除按钮
            const midIndex = Math.floor(this.positions.length / 2);
            const midPosition = this.positions[midIndex];

            // 创建删除按钮
            this.createDeleteButton(midPosition, this.currentMeasureGroupId);

            // 将线段添加到已完成线段数组
            this.allLineEntities.push(this.lineEntity);
            this.lineEntity = null;
        }

        // 计算总距离并触发结束事件
        this.measureDistance = parseFloat(this.calculateDistance(this.positions));
        this.MeasureEndEvent.raiseEvent(this.measureDistance);
    }

    // 清除临时移动顶点
    if (this.moveVertexEntity) {
        this.viewer.entities.remove(this.moveVertexEntity);
        this.moveVertexEntity = null;
    }

     // 修改这部分，不重置 currentMeasureGroupId
     this.positions = [];
     this.tempPositions = [];
     // this.currentMeasureGroupId = null; // 删除这行

    // 禁用测量（保留图形，仅移除交互事件）
    this.deactivate();
}


    // 计算多点总距离
    calculateDistance(points) {
        let total = 0;
        for (let i = 1; i < points.length; i++) {
            total += Cartesian3.distance(points[i - 1], points[i]);
        }
        return total.toFixed(3); // 保留3位小数
    }

    // 获取有效坐标（处理未拾取到地形的情况）
    getValidPosition(screenPosition) {
        let position = this.viewer.scene.pickPosition(screenPosition);
        if (!position) {
            const ellipsoid = this.viewer.scene.globe.ellipsoid;
            position = this.viewer.scene.camera.pickEllipsoid(screenPosition, ellipsoid);
        }
        return position;
    }

    // 注册事件
    registerEvents() {
        this.handler.setInputAction(this.leftClickHandler.bind(this), ScreenSpaceEventType.LEFT_CLICK);
        this.handler.setInputAction(this.mouseMoveHandler.bind(this), ScreenSpaceEventType.MOUSE_MOVE);
        this.handler.setInputAction(this.rightClickHandler.bind(this), ScreenSpaceEventType.RIGHT_CLICK);
    }

    // 解除事件
    unRegisterEvents() {
        this.handler.removeInputAction(ScreenSpaceEventType.LEFT_CLICK);
        this.handler.removeInputAction(ScreenSpaceEventType.MOUSE_MOVE);
        this.handler.removeInputAction(ScreenSpaceEventType.RIGHT_CLICK);
    }
}

export default CesiumMeasureDistance;
